package com.supermarket.api.common.exception;

import com.supermarket.api.common.BaseResponse;
import com.supermarket.api.common.ErrorMessage;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局错误处理
 * @author li
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	@ResponseBody
	@ExceptionHandler(value = Exception.class)
    public Object handleException(HttpServletRequest request, Exception e) {
        e.printStackTrace();

        String msg = e.getMessage();
        if (e instanceof BaseException) {
            int code = ((BaseException) e).getCode();
            return BaseResponse.errorJson(code, msg);
        } else if (e instanceof IllegalArgumentException) {
            return BaseResponse.errorJson(ErrorMessage.ERR_PARAM_ERROR.getCode(), msg);
        } else {
            //默认系统错误
            return BaseResponse.errorJson(ErrorMessage.ERR_SYSTERM);
        }
    }
}